import axios from "axios";
import axiosRetry from "axios-retry";
// import { baseUrl } from "@/config/env";
import { getStore } from "@/utils/store";
import { validatenull } from "@/utils/validate.js";
import router from "@/router/router.js";
import store from "@/store/index.js";
import { Notify } from "vant";
import { setStore, removeStore } from "@/utils/store";

const client = axios.create({
  // baseURL,
  timeout: 5000,
  // 跨域请求时是否需要使用凭证
  withCredentials: true,
  headers: {
    // "Content-Type": "multipart/form-data;application/json;charset=utf-8",
    // get: {
    //   "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    // },
    // post: {
    //   "Content-Type": "multipart/form-data;application/json;charset=utf-8",
    // },
  },
  // 在向服务器发送请求前，序列化请求数据
  // transformRequest: [
  //   function (data) {
  //     data = JSON.stringify(data);
  //     return data;
  //   },
  // ],
  // // 在传递给 then/catch 前，修改响应数据
  // transformResponse: [
  //   function (data) {
  //     if (typeof data === "string" && data.startsWith("{")) {
  //       data = JSON.parse(data);
  //     }
  //     return data;
  //   },
  // ],
});

// 当请求失败后，自动重新请求，只有3次失败后才真正失败
axiosRetry(client, { retries: 3 });

// 请求拦截
client.interceptors.request.use(
  (config) => {
    const token = getStore({ name: "token" });
    const meta = config.meta || {};
    const isToken = meta.isToken === false;
    if (!isToken && token) {
      config.headers["Authorization"] = token;
    }
    return config;
  },
  (error) => {
    error.data = {};
    error.data.msg = "服务器异常，请联系管理员！";
    // Notify({ type: "danger", duration: 2000, message: error.data.msg });
    return Promise.reject(new Error(error));
  }
);

// 响应拦截
client.interceptors.response.use(
  (res) => {
    // 更换 token
    const newToken = res.headers.token;
    if (!validatenull(newToken)) {
      removeStore({ name: "token" });
      setStore({ name: "token", content: newToken });
    }

    const code = Number(res.data.code) || 200;
    const message = res.data.message || "未知错误！";

    if (code === 401) {
      Notify({
        type: "warning",
        duration: 1000,
        message: "登入已过期，请重新登入！",
      });
      store.commit("SET_TOKEN", "");
      store.commit("SET_USERIFNO", {});
      router.push("/login");
      return Promise.reject(new Error(message));
    }

    if (code !== 200 && code !== 400) {
      return Promise.reject(new Error(message));
    }
    return res;
  },
  (error) => {
    error.data = {};
    error.data.msg = "服务器异常！";
    // Notify({ type: "danger", duration: 2000, message: error.data.msg });
    return Promise.reject(new Error(error));
  }
);

export default client;
